package com.lianxueda.drawing.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lianxueda.drawing.domain.pojo.Schedules;

import com.lianxueda.drawing.mapper.SchedulesMapper;
import com.lianxueda.drawing.service.SchedulesService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 29264
 */
@Service
public class SchedulesServiceImpl extends ServiceImpl<SchedulesMapper, Schedules>
implements SchedulesService {


    @Autowired
    private  SchedulesMapper schedulesMapper;


    @Override
    public void saveOrUpdateSchedules(List<Schedules> schedules) {
        if (schedules == null || schedules.isEmpty()) {
            return;
        }

        // 假设所有传入的 Schedules 对象具有相同的 courseId
        Integer courseId = schedules.get(0).getCourseId();

        // 1. 找出数据库中具有相同 courseId 的所有记录
        List<Schedules> existingSchedules = schedulesMapper.findByCourseId(courseId);

        // 2. 找出传入的 schedules 列表中已有的记录的 ids
        List<Integer> incomingIds = schedules.stream()
                .filter(schedule -> schedule.getId() != null)
                .map(Schedules::getId)
                .collect(Collectors.toList());

        // 3. 找出数据库中存在但不在传入列表中的记录的 ids
        List<Integer> idsToDelete = existingSchedules.stream()
                .filter(existingSchedule -> !incomingIds.contains(existingSchedule.getId()))
                .map(Schedules::getId)
                .collect(Collectors.toList());

        if (!idsToDelete.isEmpty()) {
            // 删除数据库中多余的记录
            schedulesMapper.deleteAllById(idsToDelete);
            System.out.println(idsToDelete + " 被删除的 IDs");
        }

        // 4. 保存或更新前端传来的所有记录
        schedulesMapper.saveAll(schedules);
    }



}
